// Copyright (C) 2012 Denis Shienkov <denis.shienkov@gmail.com>
// Copyright (C) 2012 Laszlo Papp <lpapp@kde.org>
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include "console.h"
#include <QMimeData>
#include <QScrollBar>
#include <QInputEvent>
#include <QCoreApplication>
Console::Console(QWidget *parent) :
    QPlainTextEdit(parent)
{
    document()->setMaximumBlockCount(100);
    QPalette p = palette();
    p.setColor(QPalette::Base, Qt::black);
    p.setColor(QPalette::Text, Qt::green);
    setPalette(p);
}

void Console::putData(const QByteArray &data, int locale)
{
	//qDebug()<<data;
	insertPlainText(locale==0?QString::fromUtf8(data):QString::fromLocal8Bit(data));

	QScrollBar *bar = verticalScrollBar();
	bar->setValue(bar->maximum());
	QCoreApplication::processEvents();
}

void Console::setLocalEchoEnabled(bool set)
{
    m_localEchoEnabled = set;
}

void Console::keyPressEvent(QKeyEvent *e)
{
	if (m_localEchoEnabled)
		QPlainTextEdit::keyPressEvent(e);
	emit getData(e->text().toUtf8());
}

void Console::insertFromMimeData(const QMimeData *source)
{
	emit getData(source->text().toUtf8());
	return QPlainTextEdit::insertFromMimeData(source);
}

void Console::mousePressEvent(QMouseEvent *e)
{
    setFocus();
	return QPlainTextEdit::mousePressEvent(e);
}

void Console::mouseDoubleClickEvent(QMouseEvent *e)
{
	return QPlainTextEdit::mouseDoubleClickEvent(e);
}

void Console::contextMenuEvent(QContextMenuEvent *e)
{
	return QPlainTextEdit::contextMenuEvent(e);
}
void Console::inputMethodEvent(QInputMethodEvent *event)
{
	emit getData(event->commitString().toUtf8());
	if (m_localEchoEnabled)
		return QPlainTextEdit::inputMethodEvent(event);
}
